from flask import request
from flask_restx import Resource, Namespace, fields
from app.utils.response import success_response, error_response, paginate_response
from app.utils.auth import token_required
from app.services.user_service import UserService
from app.swagger_docs import (
    success_response_model, error_response_model, pagination_response_model,
    user_model
)

# 创建用户命名空间
user_ns = Namespace('users', description='用户管理接口')

# 定义请求模型
user_status_model = user_ns.model('UserStatus', {
    'status': fields.Boolean(required=True, description='用户状态 (true:启用, false:禁用)')
})

@user_ns.route('/')
class UserListAPI(Resource):
    """用户列表接口"""
    
    @user_ns.doc(
        description='获取用户列表',
        security='Bearer',
        params={
            'page': '页码',
            'per_page': '每页数量',
            'keyword': '搜索关键词',
            'status': '状态筛选 (0:禁用, 1:启用)'
        },
        responses={
            200: ('获取成功', pagination_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @token_required
    def get(self, current_admin):
        """获取用户列表"""
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        keyword = request.args.get('keyword', '')
        status = request.args.get('status', type=int)
        
        if status is not None:
            status = bool(status)
        
        query, page, per_page = UserService.get_list(page, per_page, keyword, status)
        return paginate_response(query, page, per_page)


@user_ns.route('/<int:user_id>')
class UserDetailAPI(Resource):
    """用户详情和删除接口"""
    
    @user_ns.doc(
        description='获取用户详情',
        security='Bearer',
        responses={
            200: ('获取成功', success_response_model),
            404: ('用户不存在', error_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @token_required
    def get(self, current_admin, user_id):
        """获取用户详情"""
        user = UserService.get_by_id(user_id)
        if not user:
            return error_response('用户不存在', 404)
        
        return success_response(user.to_dict())
    
    @user_ns.doc(
        description='删除用户',
        security='Bearer',
        responses={
            200: ('删除成功', success_response_model),
            404: ('用户不存在', error_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @token_required
    def delete(self, current_admin, user_id):
        """删除用户"""
        success = UserService.delete(user_id)
        if not success:
            return error_response('删除失败，用户不存在', 404)
        
        return success_response(message='删除成功')


@user_ns.route('/<int:user_id>/status')
class UserStatusAPI(Resource):
    """用户状态管理接口"""
    
    @user_ns.doc(
        description='更新用户状态（启用/禁用）',
        security='Bearer',
        responses={
            200: ('状态更新成功', success_response_model),
            400: ('请求参数错误', error_response_model),
            404: ('用户不存在', error_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @user_ns.expect(user_status_model, validate=True)
    @token_required
    def put(self, current_admin, user_id):
        """更新用户状态"""
        data = request.get_json()
        status = data.get('status')
        
        if status is None:
            return error_response('缺少状态参数', 400)
        
        user = UserService.update_status(user_id, status)
        if not user:
            return error_response('用户不存在', 404)
        
        return success_response(user.to_dict(), '状态更新成功') 